from marshmallow import Schema, fields, post_load
from apps.modules.admin.models.cms.cms_post import Post

class PostSchema(Schema):
    id = fields.Int(dump_only=True)
    title = fields.Str(required=True)
    slug = fields.Str(required=True)
    content = fields.Str()
    excerpt = fields.Str()
    type = fields.Str()
    featured_image = fields.Str()
    status = fields.Str()
    author_id = fields.Int()
    category_id = fields.Int()
    category_title = fields.Method('get_category_title')
    tags = fields.Method('get_tags')
    view_count = fields.Int()
    comment_count = fields.Int()
    is_featured = fields.Bool()
    is_sticky = fields.Bool()
    allow_comments = fields.Bool()
    meta_title = fields.Str()
    meta_description = fields.Str()
    meta_keywords = fields.Str()
    published_at = fields.DateTime(allow_none=True)
    deleted = fields.Bool()
    created_at = fields.DateTime()
    updated_at = fields.DateTime()

    def get_category_title(self, obj):
        """获取分类标题"""
        if obj.category:
            return obj.category.title
        return None

    def get_tags(self, obj):
        """获取标签列表"""
        tags = []
        for tag in obj.tags:
            tags.append({
                'id': tag.id,
                'title': tag.title,
                'alias': tag.alias
            })
        return tags

    @post_load
    def make_post(self, data, **kwargs):
        return Post(**data) 